from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import WebDriverException, TimeoutException
import time
import os


options = webdriver.ChromeOptions()
request_url = "http://10.130.97.9:8089/"

def start_load_test(users=3000, hatch_rate=5):
    print("into start_load_test")
    driver.get(request_url)
    time.sleep(2)
    """启动压力测试的封装函数"""
    try:
        wait = WebDriverWait(driver, 10)
        
        # 填写用户数
        locust_input = wait.until(
            EC.visibility_of_element_located((By.ID, "locust_count"))
        )
        locust_input.clear()
        locust_input.send_keys(str(users))
        
        # 填写孵化率
        rate_input = wait.until(
            EC.visibility_of_element_located((By.ID, "hatch_rate"))
        )
        rate_input.clear()
        rate_input.send_keys(str(hatch_rate))
        time.sleep(1)
        
        # 点击启动按钮
        start_btn = wait.until(
            EC.element_to_be_clickable(
                (By.XPATH, '//*[contains(text(), "Start swarming")]')
            )
        )
        driver.execute_script("arguments[0].click();", start_btn)
        print("压力测试已启动")
        
    except TimeoutException as e:
        print("启动操作超时：", str(e))
        raise

def stop_load_test():
    driver.get(request_url)
    time.sleep(2)
    """停止压力测试的封装函数"""
    try:
        wait = WebDriverWait(driver, 15)  # 停止操作可能需要更长等待
        
        # 定位停止按钮（带异常处理）
        stop_btn = wait.until(
            EC.element_to_be_clickable(
                (By.XPATH, '//div[@id="box_stop"]/a[1]')
            )
        )
        
        # 带状态检查的点击操作
        if stop_btn.is_displayed() and stop_btn.is_enabled():
            driver.execute_script("arguments[0].scrollIntoView();", stop_btn)
            stop_btn.click()
            print("已发送停止指令")
            
            # 验证停止状态
            wait.until(EC.invisibility_of_element_located(
                (By.XPATH, '//div[@id="box_stop"]')
            ))
            print("压力测试已停止")
        else:
            print("停止按钮不可操作")
            
    except TimeoutException as e:
        print("停止操作超时：", str(e))
        raise

def dlownload_csv(driver):
    # //*[@id="status"]/nav/ul/li[5]/a
    dlownload_button = EC.element_to_be_clickable(
                (By.XPATH, '//*[@id="status"]/nav/ul/li[5]/a')
            )

def init():
    global driver
    current_path = os.getcwd()
    # print(current_path)
    driver_path = current_path+"\chromedriver.exe"
    try:
        # 初始化浏览器
        driver = webdriver.Chrome(
            service=Service(driver_path),
            options=options
        )
    except WebDriverException as e:
        print("浏览器操作异常:", str(e))
    except Exception as e:
        print("系统异常:", str(e))
    finally:
        if 'driver' in locals():
            driver.quit()

# if __name__ == "__main__":
#     init()
#     start_load_test()

# //*[@id="box_stop"]/a[1]
# C:\Users\Administrator\Desktop\autotool\selenium\chromedriver.exe